package migu

import (
	"api-go/cache"
	"api-go/serializer"
	"api-go/util"
	"context"
	"fmt"
	"net/url"
	"strings"
	"time"

	"github.com/go-redis/redis/v8"
)

// 歌曲所需信息
type Song struct {
	Ids string `form:"id"`
	Br  string `form:"br"`
}

//获取歌曲信息
func (service *Song) Song() *serializer.Response {

	if val := service.Ids; val != "" {
		service.Ids = val
	} else {
		service.Ids = "69944900408"
	}

	if val := service.Br; val != "" {
		service.Br = val
	} else {
		service.Br = "1"
	}

	url := "https://c.musicapp.migu.cn/MIGUM2.0/v1.0/content/resourceinfo.do?resourceType=2&copyrightId=" + service.Ids
	//https://freetyst.nf.migu.cn/
	res, err := util.MiguGet(url)
	if err != nil {
		return err
	}
	newRes := res.(map[string]interface{})["resource"].([]interface{})
	out := map[string]interface{}{}
	if len(newRes) > 0 {
		url = "https://music.migu.cn/v3/api/music/audioPlayer/getLyric?copyrightId=" + service.Ids
		ress, err := util.MiguGet(url)
		if err != nil {
			return err
		}
		out["lyric"] = ress.(map[string]interface{})["lyric"].(string)
		data := newRes[0].(map[string]interface{})
		out["id"] = data["copyrightId"]
		out["name"] = data["songName"]
		out["singer"] = data["singer"]
		out["album"] = data["album"]
		out["picUrl"] = data["singerImg"].(map[string]interface{})[data["singerId"].(string)].(map[string]interface{})["miguImgItems"].([]interface{})[1].(map[string]interface{})["img"]
		songUrl := data["newRateFormats"].([]interface{})
		if service.Br == "3" {
			//如果没有无损格式
			if len(songUrl) > 2 {
				url := songUrl[2].(map[string]interface{})["androidUrl"].(string)
				out["url"] = strings.Replace(url, "ftp://218.200.160.122:21", "https://freetyst.nf.migu.cn", -1)
			} else {
				return serializer.ErrorResponse(serializer.CodeNoResult)
			}
		} else if service.Br == "2" {
			url := songUrl[1].(map[string]interface{})["url"].(string)
			out["url"] = strings.Replace(url, "ftp://218.200.160.122:21", "https://freetyst.nf.migu.cn", -1)
		} else {
			url := songUrl[0].(map[string]interface{})["url"].(string)
			out["url"] = strings.Replace(url, "ftp://218.200.160.122:21", "https://freetyst.nf.migu.cn", -1)
		}
	} else {
		return serializer.ErrorResponse(serializer.CodeNoResult)
	}
	return serializer.OkResponse(out)
}

//第三方调用
//https://m.music.migu.cn/migu/remoting/scr_search_tag?keyword=%E5%91%A8%E6%9D%B0%E4%BC%A6&pgc=1&rows=1&type=2
func UsingMiguSong(name, singer, br string) string {

	if a := usingMiguSearch(name, singer); a != "failed" {

		url := "https://c.musicapp.migu.cn/MIGUM2.0/v1.0/content/resourceinfo.do?resourceType=2&copyrightId=" + a

		resss, err := util.MiguGet(url)
		if err != nil {
			return "failed"
		}

		if resss.(map[string]interface{})["code"].(string) == "000000" {
			var newUrl string
			songUrl := resss.(map[string]interface{})["resource"].([]interface{})[0].(map[string]interface{})["newRateFormats"].([]interface{})
			if br == "3" {
				//如果没有无损格式
				if len(songUrl) > 2 {
					url := songUrl[2].(map[string]interface{})["androidUrl"].(string)
					newUrl = strings.Replace(url, "ftp://218.200.160.122:21", "https://freetyst.nf.migu.cn", -1)
				} else {
					newUrl = "failed"
				}
			} else if br == "2" {
				//如果没有无损格式
				if len(songUrl) > 1 {
					url := songUrl[1].(map[string]interface{})["url"].(string)
					newUrl = strings.Replace(url, "ftp://218.200.160.122:21", "https://freetyst.nf.migu.cn", -1)
				} else {
					newUrl = "failed"
				}

			} else {
				//如果没有无损格式
				if len(songUrl) > 0 {
					url := songUrl[0].(map[string]interface{})["url"].(string)
					newUrl = strings.Replace(url, "ftp://218.200.160.122:21", "https://freetyst.nf.migu.cn", -1)
				} else {
					newUrl = "failed"
				}
			}
			return newUrl
		} else {
			return "failed"
		}

	} else {
		return "failed"
	}
}

var ctx = context.Background()

//用于第三方搜索使用
func usingMiguSearch(name, singer string) string {

	key := name + " " + singer
	//此处需要对中文进行转码，否则会无法请求第三方api
	key = url.QueryEscape(key)
	//定义redis key和判断redis是否有该值
	redisKey := "migu-search-" + name + "-" + singer
	redisResult, err := cache.RedisClient.Get(ctx, redisKey).Result()
	//若redis没有该值则执行获取
	if err == redis.Nil {
		url := "https://m.music.migu.cn/migu/remoting/scr_search_tag?keyword=" + key + "&pgc=1&rows=1&type=2"

		res, err := util.MiguGet(url)
		if err != nil {
			fmt.Println(err)
			return "failed1"
		}
		//如果有搜索结果就获取id
		var ress string
		if res.(map[string]interface{})["musics"] != nil && len(res.(map[string]interface{})["musics"].([]interface{})) > 0 {
			ress = res.(map[string]interface{})["musics"].([]interface{})[0].(map[string]interface{})["copyrightId"].(string)
		} else {
			return "failed"
		}
		//转为string存入redis
		e := cache.RedisClient.Set(ctx, redisKey, ress, 72*time.Hour).Err()
		if e != nil {
			fmt.Println("err1", err)
			return "failed"
		}

		return ress
	} else if err != nil {
		return "failed"
	} else {
		//将从redis获取的结果（string类型）
		return redisResult
	}
}
